package com.zb.config;


import com.zb.common.R;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Service.class})
@ResponseBody
public class GlobalExceptionHandler {

    //全局捕获sql异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        if (ex.getMessage().contains("Deplicate entry")) {
            String name = ex.getMessage().split("")[2];
            return R.error(name + "已存在");
        }
        return R.error("未知错误");
    }
}
